var WxParse = require('../wxParse/wxParse.js');
export function getChatHistory(page) {
  const userId = wx.getStorageSync('userInfo').userId;
  const firstMessageId = page.data.firstMessageId; // 获取最早一条消息的 ID

  // 如果没有更多消息，直接返回，不进行后续请求
  if (!page.data.hasMore) {
    wx.showToast({
      title: '已展示全部信息',
      icon: 'none',
    });
    wx.stopPullDownRefresh(); // 停止下拉刷新动画
    return;
  }

  // 开始加载历史消息时，更新提示信息
  page.setData({
    refreshHint: '加载更多消息...'
  });

  wx.request({
    url: `https://open.oppomobile.com/agentplatform/app_api/conversations`,
    method: 'GET',
    header: {
      'Authorization': 'Bearer Rfl0IQuZR9vBT75i',
      'Content-Type': 'application/json'
    },
    data: {
      user: userId,
      before_id: firstMessageId, // 传递最早消息的 ID 作为分页参数
      limit: 100
    },
    success: (res) => {
      if (res.data.code === '0000') {
        const historyConversations = res.data.data.data || [];
        if (historyConversations!==null) {
          const conversationIds = historyConversations.map(conversation => conversation.id);
          console.log(conversationIds)
          // 批量获取聊天记录
          Promise.all(conversationIds.map(id => getChatDetail(page, userId, id)))
            .then(newMessages => {
              // 将所有消息按时间排序，确保最早的消息在最前面
              const sortedMessages = newMessages.flat().sort((a, b) => a.createdAt - b.createdAt);
              console.log('sortedMessages', sortedMessages);

              // 去重
              const existingMessageIds = new Set(page.data.messages.map(msg => msg.createdAt)); // 根据创建时间进行唯一性检查
              const uniqueMessages = sortedMessages.filter(message => !existingMessageIds.has(message.createdAt));

              // 组合所有消息
              const allMessages = [ ...uniqueMessages, ...page.data.messages];
              const sortedAllMessages = allMessages.sort((a, b) => a.createdAt - b.createdAt);
              console.log('allMessages', allMessages);
              console.log('sortedAllMessages', sortedAllMessages);

              page.setData({
                messages: sortedAllMessages, // 将合并后的消息数组按时间排序
                firstMessageId: historyConversations[0].id, // 更新为当前最早消息的 ID
                hasMore: res.data.data.has_more, // 更新 hasMore 标志
                refreshHint: '下拉加载更多消息...',
                conversationId: historyConversations[0].id,
              });
              if (!page.data.hasMore) {
                wx.showToast({
                  title: '已展示全部信息',
                  icon: 'none',
                });
              }
            });
        } else {
          // 如果没有更多消息，更新提示信息并禁用下拉刷新
          page.setData({
            hasMore: false, // 没有更多数据了
            refreshHint: '已展示全部信息',

          });
          wx.showToast({
            title: '已展示全部信息',
            icon: 'none',
          });
          // 延迟清空提示语句
          setTimeout(() => {
            page.setData({
              refreshHint: '',
            });
          }, 2000);
        }
      } else {
        wx.showToast({
          title: '获取历史消息失败',
          icon: 'none',
        });
      }
    },
    fail: (err) => {
      wx.showToast({
        title: '请求失败',
        icon: 'none',
      });
      console.error('Request failed:', err);
    },
    complete: () => {
      wx.stopPullDownRefresh(); // 停止下拉刷新动画
    }
  });
}

// 获取具体会话的详细聊天记录
function getChatDetail(page, userId, conversationId) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `https://open.oppomobile.com/agentplatform/app_api/chat-history`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer Rfl0IQuZR9vBT75i',
        'Content-Type': 'application/json'
      },
      data: {
        user: userId,
        conversation_id: conversationId,
      },
      success: (res) => {
        if (res.data.code === '0000') {
          let chatDetails = res.data.data?.data || [];

          if (!Array.isArray(chatDetails)) {
            chatDetails = [chatDetails];
          }

          const parsedMessages = chatDetails.map(detail => {
            const messages = [];
            const createdAt = detail.created_at; // 直接使用时间戳
            const time = dateFormat(detail.created_at);

            if (detail.query) {
              messages.push({
                role: 'user',
                content: detail.query,
                isImage: false,
                createdAt,
                time
              });
            }

            const userImageMessages = (detail.message_files || [])
              .filter(file => file.belongs_to === 'user' && file.type === 'image')
              .map(file => ({
                role: 'user',
                content: file.url,
                isImage: true,
                createdAt
              }));

            messages.push(...userImageMessages);

            if (detail.answer) {
              // 解析 AI 回答内容
              const displayContent = parseMarkdown(detail.answer, page);
              // console.log("displayContent",displayContent)

              messages.push({
                role: 'ai',
                content: detail.answer,
                isImage: false,
                createdAt,
                displayContent,
              });
            }

            const aiImageMessages = (detail.message_files || [])
              .filter(file => file.belongs_to === 'assistant' && file.type === 'image')
              .map(file => ({
                role: 'ai',
                content: file.url,
                isImage: true,
                createdAt
              }));

            messages.push(...aiImageMessages);

            // 过滤掉空内容的消息
            return messages.filter(msg => msg.content || msg.displayContent);
          }).flat();

          resolve(parsedMessages);
        } else {
          wx.showToast({
            title: '获取聊天记录失败',
            icon: 'none',
          });
          reject(res.data.message);
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '请求失败',
          icon: 'none',
        });
        console.error('Request failed:', err);
        reject(err);
      }
    });
  });
}

// 解析 Markdown 内容
function parseMarkdown(content, page) {

  WxParse.wxParse('parsedAnswer', 'md', content, page, 5);
  return page.data.parsedAnswer.nodes || [{ type: 'text', text: content }];
}


function dateFormat(timestamp) {
  if (!timestamp) return ''; // 确保 timestamp 存在
  const date = new Date(timestamp * 1000); // 假设时间戳是以秒为单位
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`; // 使用模板字符串返回格式化的日期时间
}
